#include "stm32f10x.h"

void PWM_Init(void) {
    // RCC 时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); // TIM2
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); // GPIOA

    // 时钟源
    TIM_InternalClockConfig(TIM2);

    // 时基单元
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; // 不分频
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数
    // 计数器溢出频率 
    // CK_CNT_OV = CK_CNT/(ARR+1) = CK_PSC/(PSC+1)/(ARR+1)
    // CK_CNT 为 72MHz
    TIM_TimeBaseStructure.TIM_Period = 100 + 1 - 1; // 自动重装器 ARR（*此处使用 proteus 测试时需要+1 ）
    TIM_TimeBaseStructure.TIM_Prescaler = 720 + 1 - 1; // 预分频器 PSC（*此处使用 proteus 测试时需要+1 ）
    TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; // 重复计数器
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);

    // PWM
    // 频率 Freq = CK_PSC / (PSC + 1) / (ARR + 1)
    // 占空比 Duty = CCR / (ARR + 1)
    // 分辨率 Reso = 1 / (ARR + 1)

    // OC
    TIM_OCInitTypeDef TIM_OCInitStructure;
    TIM_OCStructInit(&TIM_OCInitStructure); // 赋初始值
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; // 电平不翻转
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse = 0; // CCR 值
    TIM_OC1Init(TIM2, &TIM_OCInitStructure);

    // GPIO
    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // 复用推挽输出。输出由片上外设控制
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);


    // 运行控制
    TIM_Cmd(TIM2, ENABLE);
}


void PWM_SetCompare(uint16_t Compare) {
    TIM_SetCompare1(TIM2, Compare);
}

void PWM_SetPrescaler(uint16_t Prescaler) {
    TIM_PrescalerConfig(TIM2, Prescaler, TIM_PSCReloadMode_Immediate);
}
